import { Draw } from "../Draw/Draw";
import { stageClick } from "./handle/konva/stage-click";
import { stageMouseUp } from "./handle/konva/stage-mouseup";
import { containerDrop } from "./handle/konva/container-drop";
import { stageMouseDown } from "./handle/konva/stage-mousedown";
import { stageMouseMove } from "./handle/konva/stage-mousemove";

export class KonvaEvent {
  private draw: Draw;

  constructor(draw: Draw) {
    this.draw = draw;
  }

  /** 添加事件 */
  public initKonvaEvent() {
    const stage = this.draw.getStage();

    // 实现拖拽生成元素 - 特指 图片、媒体、文本等资源
    const container = stage.container();

    stage.on("click", (e) => stageClick(e, this.draw));
    stage.on("mouseup", (e) => stageMouseUp(e, this.draw));
    stage.on("mousedown", (e) => stageMouseDown(e, this.draw));
    stage.on("mousemove", (e) => stageMouseMove(e, this.draw));

    container.addEventListener("dragover", this.bindDragOver);
    container.addEventListener("drop", this.bindDrop.bind(this));
  }

  // 解决 bind this 的问题
  private bindDragOver = (e: DragEvent) => e.preventDefault();
  private bindDrop = (e: DragEvent) => containerDrop(e, this.draw);

  /** 移除事件 */
  public removeEvent() {
    const stage = this.draw.getStage();
    const container = stage.container();

    stage.off("click");
    stage.off("mouseup");
    stage.off("mousedown");
    stage.off("mousemove");

    container.removeEventListener("dragover", this.bindDragOver);
    container.removeEventListener("drop", this.bindDrop.bind(this));
  }
}
